﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebMatrix.WebData;
using Wicresoft.EKA.ITSM.Web.WebPortal.Models;
using Wicresoft.EKA.NRemedy;
using System.Configuration;
using Wicresoft.EKA.ITSM.Business;


namespace Wicresoft.EKA.ITSM.Web.WebPortal.Controllers
{
    [Authorize]
    //[InitializeSimpleMembership]
    public class AccountController : Controller
    {
        //
        // GET: /Account/Login

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            if (!string.IsNullOrWhiteSpace(returnUrl) && returnUrl.Contains("LogOff"))
            {
                ViewBag.ReturnUrl = "";
            }
            else
            {
                ViewBag.ReturnUrl = returnUrl;
            }
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        //[ValidateAntiForgeryToken]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            bool flag = false;
            bool flagE = false;
            if (ModelState.IsValid)
            {
                try
                {
                    ARLoginContext loginContext = new ARLoginContext(ConfigurationManager.AppSettings["ARServer"],
                        model.UserName, model.Password, ARServerFactoryWithPool.Instance);
                    //TODO Pool

                    flag = !loginContext.ServerInstance.ServerAlive;
                    if (!flag)
                    {
                        ARLoginContextPool.Instance.Add(model.UserName, loginContext);

                        // Remember me一定不要用，因为当登录的时候需要初始化Login Context;
                        FormsAuthentication.SetAuthCookie(model.UserName, false);
                        return RedirectToLocal(returnUrl);
                    }
                }
                catch (Exception e)
                {
                    flagE = true;
                    ModelState.AddModelError("", e.Message + ".   Please Contact With Administrator.");
                }
            }
            else
            {
                flag = true;
            }
            // 如果我们进行到这一步时某个地方出错，则重新显示表单
            if (model.UserName != null && model.Password != null && !flagE)
            {
                if (flag)
                {
                    ModelState.AddModelError("", "The user name or password you provided is incorrect!");
                    model.Password = string.Empty;
                }
            }
            return View(model);
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        //[ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            ARLoginContextPool.Instance.Remove(User.Identity.Name);
            FormsAuthentication.SignOut();

            return RedirectToAction("LogIn");
        }

        #region 帮助程序
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("InspectionConsole", "Home");
            }
        }

        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // 请参见 http://go.microsoft.com/fwlink/?LinkID=177550 以查看
            // 状态代码的完整列表。
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "用户名已存在。请输入其他用户名。";

                case MembershipCreateStatus.DuplicateEmail:
                    return "该电子邮件地址的用户名已存在。请输入其他电子邮件地址。";

                case MembershipCreateStatus.InvalidPassword:
                    return "提供的密码无效。请输入有效的密码值。";

                case MembershipCreateStatus.InvalidEmail:
                    return "提供的电子邮件地址无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidAnswer:
                    return "提供的密码取回答案无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidQuestion:
                    return "提供的密码取回问题无效。请检查该值并重试。";

                case MembershipCreateStatus.InvalidUserName:
                    return "提供的用户名无效。请检查该值并重试。";

                case MembershipCreateStatus.ProviderError:
                    return "身份验证提供程序返回了错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                case MembershipCreateStatus.UserRejected:
                    return "已取消用户创建请求。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";

                default:
                    return "发生未知错误。请验证您的输入并重试。如果问题仍然存在，请与系统管理员联系。";
            }
        }
        #endregion
    }
}
